package com.example.zingalbumdownloader;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.simple.parser.ParseException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.zingalbumdownloader.adapter.MySongAdapter;
import com.example.zingalbumdownloader.model.Song;
import com.example.zingalbumdownloader.utility.MyResource;
import com.example.zingalbumdownloader.utility.SongsFinder;
import com.example.zingalbumdownloader.utility.StringUtils;

public class AlbumDetail_Activity extends Activity implements OnTouchListener,
		OnCompletionListener, OnBufferingUpdateListener {
	// private ImageButton buttonPrevious;
	private ImageButton buttonPlayPause;
	// private ImageButton buttonNext;
	private TextView txtplayingSong;
	private TextView txtTimeSongPlaying;
	private SeekBar seekBar;
	private MediaPlayer mediaPlayer;

	private ListView listView;
	private ArrayList<Song> arraySong;
	private MySongAdapter adapter;

	private final Handler handler = new Handler();
	private int mediaFileLengthMiliseconds;
	private int playSongIndex = 0;

	private String urlAlbum = ""; // "http://m.mp3.zing.vn/xml/album/kmJGyknNBNNSXHRykDJTvGkG";
	private String songDuration = "";
	private NotificationManager mnotificationManager;
	private NotificationCompat.Builder notifybuilder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_albumdetail);
		Intent callIntent = getIntent();
		Bundle bundlePackage = callIntent.getBundleExtra("Package");
		if (bundlePackage != null) {
			urlAlbum = bundlePackage.getString("LINK");
			Log.d("ZING", "got: " + urlAlbum);
		}
		initView();
	}

	private void initView() {
		// buttonPrevious =
		// (ImageButton)findViewById(R.id.id_imageButtonPrevious);
		// buttonNext = (ImageButton) findViewById(R.id.id_imageButtonNext);
		txtplayingSong = (TextView) findViewById(R.id.id_textPlayingSong);
		txtTimeSongPlaying = (TextView) findViewById(R.id.id_textTimeSongPlaying);
		buttonPlayPause = (ImageButton) findViewById(R.id.id_imageButtonPlayPause);

		seekBar = (SeekBar) findViewById(R.id.id_seekBar);
		seekBar.setMax(99);
		seekBar.setOnTouchListener(AlbumDetail_Activity.this);

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnBufferingUpdateListener(AlbumDetail_Activity.this);
		mediaPlayer.setOnCompletionListener(AlbumDetail_Activity.this);

		mnotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notifybuilder = new NotificationCompat.Builder(
				AlbumDetail_Activity.this);
		notifybuilder.setSmallIcon(R.drawable.ic_downloading);

		listView = (ListView) findViewById(R.id.id_albumDetail);
		arraySong = new ArrayList<Song>();

		adapter = new MySongAdapter(AlbumDetail_Activity.this,
				R.layout.item_mysong, arraySong);
		listView.setAdapter(adapter);
		if (!urlAlbum.equals("")) {
			new showAlbumDetail().execute(urlAlbum);
		}

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				playSongIndex = position;
				// mediaPlayer.pause();
				mediaPlayer.reset();
				try {
					playSong();
				} catch (Exception e) {
				}
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						AlbumDetail_Activity.this);
				builder.setTitle("Tải bài hát sau về máy");
				builder.setMessage(arraySong.get(position).getTitle());

				builder.setNegativeButton("OK", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						File sdcarddir = new File(Environment
								.getExternalStorageDirectory()
								+ MyResource.myDirectory);
						if (!sdcarddir.exists())
							sdcarddir.mkdir();
						// final String filename =
						// StringUtils.unAccent(arraySong
						// .get(position).getTitle()) + MyResource.mp3;
						final String filename = (arraySong.get(position)
								.getTitle()) + MyResource.mp3;

						File fileDown = new File(Environment
								.getExternalStorageDirectory()
								+ MyResource.myDirectory + "/" + filename);
						if (fileDown.exists()) {
							AlertDialog.Builder builder2 = new AlertDialog.Builder(
									AlbumDetail_Activity.this);
							builder2.setTitle("File đã tồn tại");
							builder2.setMessage("Bạn có muốn ghi đè file không ?");

							builder2.setNegativeButton("Có",
									new OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											new doDownload().execute(arraySong
													.get(position).getSource(),
													filename);
										}
									});

							builder2.setPositiveButton("Không",
									new OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
										}
									});

							builder2.show();
						} else {
							new doDownload().execute(arraySong.get(position)
									.getSource(), filename);
						}
					}
				});

				builder.setPositiveButton("Hủy", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				});
				builder.show();
				return false;
			}
		});
	}

	private void playSong() {
		try {
			txtplayingSong.setText(arraySong.get(playSongIndex).getTitle());
			mediaPlayer.setDataSource(arraySong.get(playSongIndex).getSource());
			mediaPlayer.prepare();

			mediaFileLengthMiliseconds = mediaPlayer.getDuration();
			songDuration = (mediaFileLengthMiliseconds / 1000) / 60 + ":"
					+ (mediaFileLengthMiliseconds / 1000) % 60;
		} catch (Exception ex) {
			// Log.i("Stream", "" + ex.toString());
		}
		mediaPlayer.start();
		buttonPlayPause.setImageResource(R.drawable.ic_stop);

		primatySeekbarProgressUpdate();
	}

	private void nextSong() throws Exception {
		playSongIndex++;
		if (playSongIndex > arraySong.size()) {
			playSongIndex = 0;
			mediaPlayer.reset();
			playSong();
		} else {
			mediaPlayer.reset();
			playSong();
		}
	}

	public void clickPrevious(View v) {
		playSongIndex--;
		if (playSongIndex > 0) {
			mediaPlayer.reset();
			playSong();
		} else {
			playSongIndex = 0;
			mediaPlayer.reset();
			playSong();
		}
	}

	public void clickPlayPause(View v) {
		if (!mediaPlayer.isPlaying()) {
			playSong();
		} else {
			mediaPlayer.pause();
			buttonPlayPause.setImageResource(R.drawable.ic_play);
		}
	}

	public void clickNext(View v) {
		try {
			nextSong();
		} catch (Exception e) {
		}
	}

	private void primatySeekbarProgressUpdate() {
		int currentDuration = mediaPlayer.getCurrentPosition();
		String currentDurations = (currentDuration / 1000) / 60 + ":"
				+ (currentDuration / 1000) % 60;
		txtTimeSongPlaying.setText(currentDurations + " / " + songDuration);
		seekBar.setProgress((int) (((float) currentDuration / mediaFileLengthMiliseconds) * 100));

		if (mediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
				@Override
				public void run() {
					primatySeekbarProgressUpdate();
				}
			};
			handler.postDelayed(notification, 1000);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v.getId() == R.id.id_seekBar) {
			if (mediaPlayer.isPlaying()) {
				SeekBar sb = (SeekBar) v;
				int playPositionInMiliseconds = (mediaFileLengthMiliseconds / 100)
						* sb.getProgress();
				mediaPlayer.seekTo(playPositionInMiliseconds);
			}
		}
		return false;
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		seekBar.setSecondaryProgress(percent);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		try {
			nextSong();
		} catch (Exception e) {
		}
	}

	class doDownload extends AsyncTask<String, Void, Void> {

		void downloadFromUrl(String DownloadUrl, String filename)
				throws IOException {
			Log.d("ZING", "Start Download: " + DownloadUrl);
			String state = Environment.getExternalStorageState();
			if (state.equals(Environment.MEDIA_MOUNTED)) {
				File downfile = new File(
						Environment.getExternalStorageDirectory()
								+ MyResource.myDirectory + "/" + filename);
				URL url = new URL(DownloadUrl);
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.connect();
				BufferedInputStream input = new BufferedInputStream(
						url.openStream());

				long total = connection.getContentLength();
				Log.d("ZING", "total= " + total);
				BufferedOutputStream output = new BufferedOutputStream(
						new FileOutputStream(downfile));

				byte[] buffer = new byte[MyResource.byteBuffer];
				long i, count = 0;
				int percent = 0;
				Log.d("ZING", "saving");
				while ((i = input.read(buffer)) != -1) {
					count += i;
					output.write(buffer);
					percent = (int) ((count * 100 / total));
					if (total < 0) {
						notifybuilder.setProgress(100, 50, false);
						mnotificationManager.notify(0, notifybuilder.build());
					} else if (percent < 100 && percent % 3 == 0) {
						notifybuilder.setProgress(100, percent, false);
						mnotificationManager.notify(0, notifybuilder.build());
					}
				}
				Log.d("ZING", "total= " + total);
				Log.d("ZING", "count= " + count);
				output.flush();
				output.close();
				notifybuilder.setContentText("Download complete").setProgress(
						0, 0, false);
				mnotificationManager.notify(0, notifybuilder.build());

				input.close();
			}
		}

		@Override
		protected Void doInBackground(String... params) {
			notifybuilder.setContentTitle(params[1]).setContentText(
					"Downloading");
			try {
				downloadFromUrl(params[0], params[1]);
			} catch (IOException e) {
				Log.e("ZING", "download " + e.toString());
				notifybuilder.setContentText("Download Failed").setProgress(2,
						1, false);
				mnotificationManager.notify(0, notifybuilder.build());
				this.cancel(true);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.d("ZING", "Download finish");
			super.onPostExecute(result);
		}
	}

	class showAlbumDetail extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			doShowSongs(params[0]);
			return null;
		}

		void doShowSongs(String url) {
			try {
				String xmlAlbum = StringUtils.findAlbum_XML(StringUtils
						.getStringFromURLString(url));
				SongsFinder.findSongs(xmlAlbum, arraySong);
				Log.d("ZING", "Finded album");
			} catch (ParseException e) {
				Log.e("ZING", "showAlbump " + e.toString());
				this.cancel(true);
			} catch (IOException e) {
				Log.e("ZING", "showAlbumio " + e.toString());
				this.cancel(true);
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			adapter.notifyDataSetChanged();
			Log.d("ZING", "So luong Songs: " + arraySong.size());
		}
	}

	@Override
	protected void onDestroy() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.stop();
		}
		super.onDestroy();
	}
}
